//
//  QAuthController.swift
//  swift-微博
//
//  Created by chenrin on 2016/12/19.
//  Copyright © 2016年 zhuoheng. All rights reserved.
//

import UIKit
import SVProgressHUD

class QAuthController: UIViewController {

    fileprivate let WB_App_Key = "3010523872"
    fileprivate let App_Secret = "3d2bbd9af4bc5a7036afccce5aaa51ef"
    fileprivate let WB_redirect_uri = "http://www.baidu.com"
    
    // MARK:- 懒加载
    lazy var webView: UIWebView = {
        let webView = UIWebView()
        webView.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: UIScreen.main.bounds.size.height)
        webView.delegate = self
        return webView
    }()
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.white
        SVProgressHUD.show(withStatus: "正在加载中...")
        SVProgressHUD.setDefaultMaskType(.black)
        navigationItem.title = "卓之恒的微博"
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "关闭", style: .plain, target: self, action: #selector(closeItem))
        
        let urlStr = "https://api.weibo.com/oauth2/authorize?client_id=\(WB_App_Key)&redirect_uri=\(WB_redirect_uri)"
        let url = URL(string: urlStr)
        let request = URLRequest(url: url!)
        webView.loadRequest(request)
        view.addSubview(webView)
        
       
    }
    func closeItem(){
        dismiss(animated: true, completion: nil)
    }
   
   
}
// MARK:- webView的协议
extension QAuthController:UIWebViewDelegate{
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        print(request)
        //1.判断是否是授权回调页
        let urlStr = request.url?.absoluteString
        if !(urlStr!.hasPrefix("http://www.baidu.com")) {
            //登录界面
            return true
        }
        //2.判断是否授权成功
        let codeStr = "code="
        //query:参数
        if (request.url?.query?.hasPrefix(codeStr))!{
            //授权成功
            //取出已经授权的RequestToken
           let code = request.url?.query?.substring(from: codeStr.endIndex)
            print(code!)
            print("授权成功")
            
            //利用得到的code去请求AccessToken
            let url = "https://api.weibo.com/oauth2/access_token"
            let params = ["client_id":WB_App_Key,"client_secret":App_Secret,"grant_type":"authorization_code","code":code!,"redirect_uri":WB_redirect_uri]
            NetworkTools.requestData(methodType: .POST, urlString: url, parameters: params, finishedCallback: { (result) in
                //1.将数据转换成字典
                guard let resultDict = result as? [String:Any] else{
                    return
                }
                
                let oAuthModel = OAuthModel(dict: resultDict)
                oAuthModel.loadUserInfo()
                
                //归档模型
                //oAuthModel.saveAccount()
                
            })
           
        }else{
            //取消授权
            print("取消授权")
            //关闭界面
            closeItem()
        }
        
        return false
    }
    
    ///开始加载
    func webViewDidStartLoad(_ webView: UIWebView) {
        
    }
    ///加载结束
    func webViewDidFinishLoad(_ webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    
    
}

